import sqlite3
import subprocess
import threading

import wx

container_dock = -101
container_desktop = -100
table_name_favorites = 'favorites'
table_name_double_favorites = 'doubleFavorites'
table_name_ease_favorites = 'easeFavorites'

apps_in_dock = []
apps_in_desktop = []
widgets_info_in_desktop = []
folders_info_in_desktop = []

table_keys = [
    '_id', 'title', 'intent', 'container', 'screen', 'cellX', 'cellY', 'spanX', 'spanY', 'itemType', 'appWidgetId',
    'icon', 'appWidgetProvider', 'modified', 'restored', 'profileId', 'rank', 'options', 'appWidgetSource'
]


def table_exists(cursor, table_name):
    cursor.execute("""
        SELECT COUNT(*) 
        FROM sqlite_master 
        WHERE type='table' AND name=?
    """, (table_name,))
    return cursor.fetchone()[0] == 1


def list_tables(cursor):
    cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
    all_tables = cursor.fetchall()
    return [table[0] for table in all_tables]


def fetch_data_by_container(cursor, table_name, container_value):
    query = f"SELECT * FROM {table_name} WHERE container = ?"
    cursor.execute(query, (container_value,))
    return cursor.fetchall()


# widget
def fetch_data_by_appWidgetId(cursor, table_name):
    query = f"SELECT * FROM {table_name} WHERE appWidgetId > ?"
    cursor.execute(query, (0,))
    return cursor.fetchall()


# 文件夹
def fetch_data_by_itemType(cursor, table_name):
    query = f"SELECT * FROM {table_name} WHERE itemType = ?"
    cursor.execute(query, (2,))
    return cursor.fetchall()


def get_column_names(cursor, table_name):
    """Get column names for a specific table."""
    cursor.execute(f"PRAGMA table_info({table_name})")
    return [column[1] for column in cursor.fetchall()]


def get_component_name(text):
    component_start = "component="
    intent_info = text.split(';')
    for info in intent_info:
        if info.startswith(component_start):
            return info[len(component_start):]
    return ""


class MyFrame(wx.Frame):
    def __init__(self):
        super().__init__(None, title="提取布局", size=(600, 400))
        self.Centre()
        panel = wx.Panel(self)

        # 保存位置选择

        # 文本框
        self.text_ctrl = wx.TextCtrl(panel, style=wx.TE_MULTILINE | wx.HSCROLL)

        # 输入框

        # 两个按钮
        self.clear_text_button = wx.Button(panel, label="拉取手机布局数据库")
        self.clear_text_button.Bind(wx.EVT_BUTTON, self.pull_database)
        self.make_layout_button = wx.Button(panel, label="制作生成布局文件")
        self.make_layout_button.Bind(wx.EVT_BUTTON, self.make_layout)
        button_box = wx.BoxSizer(wx.HORIZONTAL)
        button_box.Add(self.clear_text_button, 1, wx.EXPAND | wx.ALL, 5)
        button_box.Add(self.make_layout_button, 1, wx.EXPAND | wx.ALL, 5)

        # 创建布局管理器（垂直BoxSizer）
        vbox = wx.BoxSizer(wx.VERTICAL)
        vbox.Add(self.text_ctrl, 1, wx.EXPAND | wx.ALL, 5)
        vbox.Add(button_box, 0, wx.EXPAND, 5)

        # 设置面板的布局
        panel.SetSizer(vbox)

    def pull_database(self, event):
        thread = threading.Thread(target=self.pull_database1, args=())
        thread.daemon = True
        thread.start()

    def pull_database1(self):
        self.text_ctrl.SetValue("抓取database中......")
        result = subprocess.run(
            "adb pull data/user_de/0/com.zte.mifavor.launcher/databases", shell=True,
            stdout=subprocess.PIPE, stderr=subprocess.PIPE).returncode
        if result == 0:
            self.text_ctrl.SetValue("Successful!  抓取database成功")
        else:
            self.text_ctrl.SetValue("Failed!  抓取database失败，请检查手机是否连接")

    def make_layout(self, event):
        thread = threading.Thread(target=self.make_layout2, args=())
        thread.daemon = True
        thread.start()

    def make_layout2(self):
        self.text_ctrl.SetValue("制作布局文件")
        conn = sqlite3.connect('databases/launcher.db')
        cur = conn.cursor()
        try:
            tables = list_tables(cur)
            if tables:
                # 遍历每个表
                for table in tables:
                    apps_in_dock.clear()
                    apps_in_desktop.clear()
                    widgets_info_in_desktop.clear()
                    folders_info_in_desktop.clear()
                    self.text_ctrl.AppendText(f"\n\n{table}:")
                    cur.execute("SELECT * FROM " + table)
                    # 桌面folder
                    results = fetch_data_by_itemType(cur, table)
                    if results:
                        for content in results:
                            folder_info = [content[0], content[1], content[4], content[5], content[6], content[7],
                                           content[8]]
                            folders_info_in_desktop.append(folder_info)
                    else:
                        self.text_ctrl.AppendText(f"\n{table} 中没有文件夹")
                    # 桌面folder

                    # 桌面folder应用
                    for folder_info in folders_info_in_desktop:
                        apps_in_folder_info = []
                        folder_id = folder_info[0]
                        self.text_ctrl.AppendText(f"\n文件夹<{folder_info[1]}>中的应用有:")
                        results = fetch_data_by_container(cur, table, folder_id)
                        if results:
                            for content in results:
                                self.text_ctrl.AppendText(f"{content[1]};")
                                app_in_folder_info = [content[0], content[1], content[4], content[5], content[6],
                                                      content[7],
                                                      content[8]]
                                apps_in_folder_info.append(app_in_folder_info)
                        else:
                            self.text_ctrl.AppendText("  Error!   没有找到文件夹中的应用!!!")
                    # 桌面folder应用

                    # 桌面widget
                    results = fetch_data_by_appWidgetId(cur, table)
                    if results:
                        self.text_ctrl.AppendText("\n桌面widget有:")
                        for content in results:
                            self.text_ctrl.AppendText(f"{content[12]};")
                            widget_info = [content[4], content[5], content[6], content[7], content[8], content[12]]
                            widgets_info_in_desktop.append(widget_info)
                    else:
                        self.text_ctrl.AppendText("  Warning!   桌面没有widget，请检查是否正确!!!")
                    # 桌面widget

                    # 桌面非文件夹应用
                    results = fetch_data_by_container(cur, table, container_desktop)
                    if results:
                        self.text_ctrl.AppendText("\n桌面应用有:")
                        for content in results:
                            if content[9] == 0:
                                self.text_ctrl.AppendText(f"{content[1]};")
                                result = get_component_name(content[2])
                                if "/." in result:
                                    package_name = result.split('/.')[0]
                                    class_name = result.split('/.')[0] + "." + result.split('/.')[1]
                                    app_info = [content[1], package_name, class_name]
                                    apps_in_desktop.append(app_info)
                                elif "/" in result:
                                    package_name = result.split('/')[0]
                                    class_name = result.split('/')[1]
                                    app_info = [content[1], package_name, class_name]
                                    apps_in_desktop.append(app_info)
                    else:
                        self.text_ctrl.AppendText("  Warning!   桌面没有应用，请检查是否正确!!!")
                    # 桌面非文件夹应用

                    # dock区应用
                    results = fetch_data_by_container(cur, table, container_dock)
                    if results:
                        self.text_ctrl.AppendText("\ndock区应用有:")
                        for content in results:
                            self.text_ctrl.AppendText(f"{content[1]};")
                            app_info = [content[1], content[4]]
                            apps_in_dock.append(app_info)
                    else:
                        self.text_ctrl.AppendText("  Warning!   dock区没有应用，请检查是否正确!!!")
                    # dock区应用
            else:
                self.text_ctrl.AppendText("  Error!   数据库中没有表，请检查是否正确!!!")
        finally:
            # 关闭游标和连接
            cur.close()
            conn.close()


if __name__ == '__main__':
    app = wx.App()
    frame = MyFrame()
    frame.Show()
    app.MainLoop()
